package config.interceptor;

import com.alibaba.fastjson.JSON;
import com.ggkt.common.utils.web.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Aspect
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    	//如果有对外的接口，不需要登录，可以在接口里面添加特定的url,比如ip:port/admin/foreign/xxx  可以把下面的admin换成foreign
    	String requestURI = request.getRequestURI();
    	if (requestURI.contains("admin")) {
			return true;
		}
    	//等登录接口定好以后，下面获取用户信息，比如  adminUser 然后判断如果adminUser为空的话，抛出异常"用户未登陆或已登陆超时sssss"
    	String sessionUser = null;
        if (sessionUser==null) {
            log.error("the user is null");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            RestResult res = RestResult.error("用户未登陆或已登陆超时");
            writer.write(JSON.toJSONString(res));
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
